<template>
    <div class="divs" >
        <div v-if="items1" v-dompurify-html="marked(items1)" >
<!-- {{ marked(items1) }} -->

        </div>
        <div v-dompurify-html="marked(items)"></div>

    </div>
    <div>
        <el-input v-model="text" placeholder="Approved by" style="width: 240px;" clearable />
        <el-button type="primary" @click="onSubmit">Query</el-button>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from "vue";
import { marked } from 'marked';
const items = ref('')
const text = ref('')
const items1 = ref('')
const objsS = ref({
    model: "Pro/deepseek-ai/DeepSeek-R1",
    top_k: 50,
    temperature: 0.6,
    top_p: 0.95,
    stream: true,
    messages: [{ role: "user", content: "鲨鱼为什么也会被淹死" }]
})
const onSubmit = () => {

    objsS.value.messages[0].content = text.value
    console.log(objsS.value)
    goDialogue(objsS.value)
}
const goDialogue = async (e: any) => {
    const options = {
        method: 'POST',
        headers: { Authorization: 'Bearer sk-tbmfnjbitqqdwrufldkhtnuwavmwwjbuhcjpxywphlokatbo', 'Content-Type': 'application/json' },
        body: JSON.stringify(e)
    };

    try {
        const response = await fetch('https://api.siliconflow.cn/v1/chat/completions', options)
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        let partialData = '';
        let isDialogue = true
        while (isDialogue) {
            const { done, value } = await reader.read();
            if (done) break;

            const chunk = decoder.decode(value, { stream: true });
            partialData += chunk;

            // 处理可能的多条消息（按换行符分割）
            const lines = partialData.split('\n');
            partialData = lines.pop() || ''; // 保留未完成的行

            for (const line of lines) {
                if (line.trim()) {
                    if (line.startsWith('data: ')) {
                        try {
                            let data = goIsEnd(line.slice(6))
                            if (JSON.stringify(data) !== '{}' && data.choices[0].delta) {
                                console.log('----->', data.choices[0].delta)
                                let txt = data.choices[0].delta.content
                                let txt1 = data.choices[0].delta.reasoning_content
                                if (txt) {
                                    items.value = items.value + txt
                                    // obj.text = obj.text + txt
                                    // this.$set(obj,"text",obj.text)
                                }
                                if (txt1) {
                                    items1.value = items1.value + txt1
                                }

                            } else {
                                //关闭循环
                                isDialogue = false
                            }

                        } catch (e) {
                            console.error('解析错误:', e);
                        }
                    }
                }
            }
        }
    } catch (error) {
        console.error("Error fetching stream:", error);
    }

}

const goIsEnd = function (ele: string) {

    if (ele === '[DONE]') {
        return {}
    } else {
        return JSON.parse(ele)
    }
}



//执行函数

</script>

<style scoped>
.divs {
    background-color: #fff;
    width: 100%;
    min-height: 300px;

    height: auto;
}
</style>